package org.jash.demo2205.shop

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.alibaba.android.arouter.launcher.ARouter
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.BaseTransientBottomBar.BaseCallback
import com.google.android.material.snackbar.Snackbar
import org.jash.demo2205.BR
import org.jash.demo2205.R
import org.jash.demo2205.databinding.FragmentCartBinding
import org.jash.demo2205.entity.Cart
import org.jash.demo2205.entity.CartItem
import org.jash.demo2205.mvvm.BaseFragment
import org.jash.demo2205.utils.CommonAdapter
import org.jash.demo2205.utils.Event
import org.jash.demo2205.utils.MyItemAnimator

/**
 * A simple [Fragment] subclass.
 * Use the [CartFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class CartFragment : BaseFragment<FragmentCartBinding, CartViewModel>() {
    lateinit var cart:Cart
    lateinit var adapter: CommonAdapter<CartItem>
    override fun initData() {
        cart = Cart()
        adapter = CommonAdapter({R.layout.item_cart to BR.item}, cart.data)
        viewModel.cartLiveData.observe(viewLifecycleOwner) {
            adapter.clear()
            adapter += it
            if (it.isEmpty()) {
                Toast.makeText(requireContext(), "你还没加入任何商品", Toast.LENGTH_SHORT).show()
            }
        }
        viewModel.deleteLiveData.observe(viewLifecycleOwner) {
            Toast.makeText(requireContext(), it, Toast.LENGTH_SHORT).show()
        }
        viewModel.getCart()
    }

    override fun initView() {
        binding.cart = cart
        binding.recycler.adapter = adapter
        binding.recycler.itemAnimator = MyItemAnimator()
//        binding.recycler.itemAnimator?.removeDuration = 2000
        binding.all.addOnCheckedStateChangedListener { _, state -> cart.allChecked = state }
        binding.pay.setOnClickListener {
            ARouter.getInstance().build("/shop/pay")
                .withString("info", cart.data.filter(CartItem::checked).joinToString("\n") { "${it.goods_desc} ${it.goods_default_price}x${it.count}" })
                .withFloat("total", cart.total)
                .navigation()
        }
    }
    @Event("更新购物车")
    fun updateCart(s:String) {
        cart.notifyPropertyChanged(BR.allChecked)
    }
    @Event("删除购物车")
    fun deleteCart(item:CartItem) {
//        MaterialAlertDialogBuilder(requireContext())
//            .setTitle("确认删除")
//            .setMessage("确定要删除${item.goods_desc}吗?")
//            .setNegativeButton("否", null)
//            .setPositiveButton("是") { _, _ ->
//                viewModel.deleteCart(item.id)
//                adapter.removeIf { it.id == item.id }
//                cart.notifyPropertyChanged(BR.allChecked)
//            }.show()
        val index = adapter.data.indexOfFirst { it.id == item.id }
        adapter.removeIf { it.id == item.id }
        Snackbar.make(binding.root, "删除${item.goods_desc}", Snackbar.LENGTH_LONG)
            .setAction("撤销") {
                adapter.add(index, item)
            }
            .addCallback(object :BaseCallback<Snackbar>() {
                override fun onDismissed(transientBottomBar: Snackbar?, event: Int) {
                    if (event != DISMISS_EVENT_ACTION) {
                        viewModel.deleteCart(item.id)
                        cart.notifyPropertyChanged(BR.allChecked)
                    }
                }
            }).show()
    }
}